package mts.messages;

import mts.constants.MessageType;

import org.apache.log4j.Logger;

public abstract class Message {
	private static final Logger log = Logger.getLogger(Message.class);
	
	public static final int INDEX_MESSAGE_TYPE = 0;
	
	private final MessageType messageType;

	public abstract byte[] serialize();
	public MessageType getMessageType() {
		return messageType;
	}
	
	protected Message(MessageType messageType) {
		this.messageType = messageType;
	}
	
	public static Message deserialize(byte[] data) {
	
		MessageType messageType = MessageType.valueOf(data[INDEX_MESSAGE_TYPE]);
		if (messageType == MessageType.STATUS_REPLY) {
			StatusMessage statusMessage = StatusMessage.deserialize(data);
			log.info("Status Message deserialized - " + statusMessage.toString());
			return statusMessage;			
		} else if (messageType == MessageType.CAR_ERROR) {
			CarErrorMessage carErrormessage = CarErrorMessage.deserialize(data);
			log.info("Car Error Message deserialized - " + carErrormessage.toString());
						
			return carErrormessage;
		} else if (messageType == MessageType.EC_INIT_MSG) {
			ElevatorControllerInitMessage initMessage = ElevatorControllerInitMessage.deserialize(data);
			log.info("Elevator Controller Message deserialized - " + initMessage.toString());
			
			return initMessage;
		} else if (messageType == MessageType.EVENT_MSG) {
			EventTimeStampMessage eventMessage = EventTimeStampMessage.deserialize(data);
			log.info("Event Timestamp Message deserialized - " + eventMessage.toString());
			
			return eventMessage;
		} else {
			log.error("Unknown message type of {" + messageType + "}");
			return null;
		}
	}
	
}
